package top.zhouze.common.util;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.function.Consumer;

/**
 * @author 周仄
 * @since 2024/2/2 13:45
 */
public class DatabaseUtil {

    public static void exportDatabase(Context context,String dbName,String exportPath) {
        File databaseFile = context.getDatabasePath(dbName);
        File exportDir = new File(Environment.getExternalStorageDirectory(), exportPath);
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        String time = StrUtil.getNowTime("yyyyMMddHHmmss");
        File exportFile = new File(exportDir, dbName+"-"+time+".db");
        try {
            FileChannel source = new FileInputStream(databaseFile).getChannel();
            FileChannel destination = new FileOutputStream(exportFile).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 遍历游标
     *
     * @param cursor   光标
     * @param consumer 消费者
     */
    public static void forEachCursor(Cursor cursor, Consumer<Cursor> consumer) {
        if(cursor!=null&&cursor.moveToFirst()){
            do{
                consumer.accept(cursor);
            }while(cursor.moveToNext());
            cursor.close();
        }
    }

}
